package com.mm.cloth.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mm.cloth.AddClothesActivity;
import com.mm.cloth.ClothesDetailActivity;
import com.mm.cloth.MainActivity;
import com.mm.cloth.R;
import com.mm.cloth.adapter.CategoryAdapter;
import com.mm.cloth.adapter.ClothesAdapter;
import com.mm.cloth.adapter.SeasonAdapter;
import com.mm.cloth.api.ApiClient;
import com.mm.cloth.api.ApiService;
import com.mm.cloth.model.Category;
import com.mm.cloth.model.Clothes;
import com.mm.cloth.model.request.CategoryRequest;

import com.mm.cloth.model.response.ApiResponse;
import com.mm.cloth.model.response.ClothesListResponse;
import com.mm.cloth.utils.ApiTestHelper;
import com.mm.cloth.utils.ItemSpacingDecoration;
import com.mm.cloth.utils.LoginCheckUtil;
import com.mm.cloth.utils.NetworkUtil;
import com.mm.cloth.utils.TokenDebugHelper;
import com.mm.cloth.utils.TokenManager;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

public class WardrobeFragment extends Fragment {

    private static final String TAG = "WardrobeFragment";

    // UI组件
    private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView rvCategories;
    private RecyclerView rvSeasons;
    private RecyclerView rvClothes;
    private TextView tvEmpty;
    private FloatingActionButton fabAdd;
    private TextView tvAddCategory;
    private TextView tvFinishEdit;
    private EditText etSearch;
    private ImageView ivClearSearch;
    private TextView tvSearch;
    private LinearLayout emptyStateLayout;
    private LinearLayout loadingLayout;
    private TextView tvNoMore;

    // 数据
    private CategoryAdapter categoryAdapter;
    private SeasonAdapter seasonAdapter;
    private ClothesAdapter clothesAdapter;
    private List<Category> categories = new ArrayList<>();
    private List<String> seasons = new ArrayList<>();
    private List<Clothes> clothesList = new ArrayList<>();
    private boolean isLoading = false;
    private boolean isLastPage = false;
    private int currentPage = 1;
    private int pageSize = 10;
    private int selectedCategoryPosition = 0;
    private String searchKeyword = "";
    private long lastRefreshTime = 0;

    // 存储最近的登录回调
    private LoginCheckUtil.LoginCallback pendingLoginCallback = null;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        try {
            View view = inflater.inflate(R.layout.fragment_wardrobe, container, false);
            initViews(view);
            setupCategories();
            setupSeasons();
            setupClothesRecyclerView();
            setupListeners();
            loadClothes(true);
            return view;
        } catch (Exception e) {
            Log.e(TAG, "WardrobeFragment onCreateView 异常", e);
            throw e;
        }
    }

    @Override
    public void onResume() {
        super.onResume();

        Log.d(TAG, "WardrobeFragment onResume");

        // 检查是否需要在登录后刷新
        checkAndRefreshAfterLogin();

        // 强制检查和刷新分类数据
        forceRefreshCategoriesIfNeeded();

        // 如果距离上次刷新超过5秒，刷新数据
        if (System.currentTimeMillis() - lastRefreshTime > 5000) {
            if (getActivity() != null && LoginCheckUtil.isLoggedIn(getActivity())) {
                // 如果用户已登录，刷新数据
                currentPage = 1;
                isLastPage = false;
                loadClothes(true);
                lastRefreshTime = System.currentTimeMillis();
            }
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        Log.d(TAG, "WardrobeFragment setUserVisibleHint: " + isVisibleToUser);

        if (isVisibleToUser && isResumed()) {
            Log.d(TAG, "WardrobeFragment变为可见且已Resume，强制刷新分类数据");

            // Fragment变为可见时，强制重新加载分类数据
            if (getActivity() != null && LoginCheckUtil.isLoggedIn(getActivity())) {
                Log.d(TAG, "WardrobeFragment用户已登录，立即重新加载分类");
                loadCategoriesFromApi();
            } else {
                Log.d(TAG, "WardrobeFragment用户未登录，加载本地分类");
                loadCategoriesFromLocal();
            }
        }
    }

    /**
     * 处理返回键，如果在编辑模式则退出编辑模式
     */
    public boolean onBackPressed() {
        if (categoryAdapter != null && categoryAdapter.isEditMode()) {
            finishEditMode();
            return true; // 消费了返回键事件
        }
        return false; // 没有消费返回键事件
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        Log.d(TAG, "onActivityResult: requestCode=" + requestCode + ", resultCode=" + resultCode);
        
        // 处理登录请求的结果
        if (requestCode == LoginCheckUtil.LOGIN_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                // 用户成功登录，处理回调
                Log.d(TAG, "用户登录成功，处理回调");
                if (pendingLoginCallback != null) {
                    pendingLoginCallback.onResult(true);
                    pendingLoginCallback = null; // 清除挂起的回调
                } else {
                    // 如果没有回调，刷新数据
                    currentPage = 1;
                    isLastPage = false;
                    loadClothes(true);
                }
            } else {
                // 用户取消登录或登录失败
                Log.d(TAG, "用户取消登录或登录失败");
                if (pendingLoginCallback != null) {
                    pendingLoginCallback.onResult(false);
                    pendingLoginCallback = null; // 清除挂起的回调
                }
            }
        }
    }

    private void initViews(View view) {
        swipeRefreshLayout = view.findViewById(R.id.swipeRefreshLayout);
        rvCategories = view.findViewById(R.id.rvCategories);
        rvSeasons = view.findViewById(R.id.rvSeasons);
        rvClothes = view.findViewById(R.id.rvClothes);
        tvEmpty = view.findViewById(R.id.tvEmpty);
        fabAdd = view.findViewById(R.id.fabAdd);
        tvAddCategory = view.findViewById(R.id.tvAddCategory);
        tvFinishEdit = view.findViewById(R.id.tvFinishEdit);
        etSearch = view.findViewById(R.id.etSearch);
        ivClearSearch = view.findViewById(R.id.ivClearSearch);
        tvSearch = view.findViewById(R.id.tvSearch);
        emptyStateLayout = view.findViewById(R.id.emptyStateLayout);
        loadingLayout = view.findViewById(R.id.loadingLayout);
        tvNoMore = view.findViewById(R.id.tvNoMore);
    }

    private void setupCategories() {
        // 初始化默认分类数据（包含"全部"分类）
        categories.clear(); // 清空可能存在的旧数据
        categories.add(new Category(0, "全部"));

        categoryAdapter = new CategoryAdapter(getContext(), categories);

        // 使用水平布局，优化滚动体验
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
        rvCategories.setLayoutManager(layoutManager);

        // 优化RecyclerView滚动性能
        rvCategories.setHasFixedSize(false); // 允许动态大小
        rvCategories.setItemViewCacheSize(20); // 增加缓存大小

        // 确保滚动条可见
        rvCategories.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        rvCategories.setHorizontalScrollBarEnabled(true);

        rvCategories.setAdapter(categoryAdapter);

        Log.d(TAG, "RecyclerView滚动优化配置完成");

        // 从API加载分类列表
        loadCategoriesFromApi();

        // 分类点击事件
        categoryAdapter.setOnCategoryClickListener(category -> {
            selectedCategoryPosition = categoryAdapter.getSelectedPosition();
            currentPage = 1;
            isLastPage = false;
            loadClothes(true);
        });
        
        // 分类长按事件，进入编辑模式
        categoryAdapter.setOnCategoryLongClickListener((category, position) -> {
            // "全部"分类不可编辑
            if (position == 0) return false;
            
            if (!LoginCheckUtil.isLoggedIn(getActivity())) {
                // 未登录，显示登录对话框
                pendingLoginCallback = isLoggedIn -> {
                    if (isLoggedIn) {
                        startEditMode();
                    }
                };
                LoginCheckUtil.checkLoginWithDialog(getActivity(), "管理分类需要登录，是否立即登录？", pendingLoginCallback);
            } else {
                startEditMode();
            }
            return true;
        });
        
        // 删除按钮点击事件
        categoryAdapter.setOnDeleteClickListener((category, position) -> {
            if (position > 0) {  // 确保不会删除"全部"分类
                showDeleteCategoryDialog(category, position);
            }
        });

        // 退出编辑模式监听器
        categoryAdapter.setOnExitEditModeListener(() -> {
            finishEditMode();
        });

        // 双击编辑监听器
        categoryAdapter.setOnCategoryDoubleClickListener((category, position) -> {
            editCategory(category, position);
        });
    }
    
    private void setupSeasons() {
        // 初始化季节数据
        seasons.addAll(Arrays.asList("全部", "春季", "夏季", "秋季", "冬季"));

        seasonAdapter = new SeasonAdapter(getContext(), seasons);
        rvSeasons.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        rvSeasons.setAdapter(seasonAdapter);

        seasonAdapter.setOnSeasonClickListener(season -> {
            // 处理季节点击事件
            currentPage = 1;
            isLastPage = false;
            loadClothes(true);
        });
    }

    private void setupClothesRecyclerView() {
        clothesAdapter = new ClothesAdapter(getContext(), clothesList);
        GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 2);
        rvClothes.setLayoutManager(layoutManager);
        
        // 设置衣物项间距
        int spacingInPixels = getResources().getDimensionPixelSize(R.dimen.clothes_item_spacing);
        rvClothes.addItemDecoration(new ItemSpacingDecoration(spacingInPixels));
        
        rvClothes.setAdapter(clothesAdapter);

        // 点击衣物项处理
        clothesAdapter.setOnClothesClickListener(clothes -> {
            if (!LoginCheckUtil.isLoggedIn(getActivity())) {
                // 未登录，显示登录对话框
                pendingLoginCallback = isLoggedIn -> {
                    if (isLoggedIn && getActivity() != null) {
                        showClothesDetail(clothes);
                    }
                };
                
                LoginCheckUtil.checkLoginWithDialog(getActivity(), "查看衣物详情需要登录，是否立即登录？", pendingLoginCallback);
            } else {
                showClothesDetail(clothes);
            }
        });

        // 添加滚动监听器实现分页加载
        rvClothes.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                GridLayoutManager layoutManager = (GridLayoutManager) recyclerView.getLayoutManager();
                if (layoutManager != null) {
                    int visibleItemCount = layoutManager.getChildCount();
                    int totalItemCount = layoutManager.getItemCount();
                    int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();

                    if (!isLoading && !isLastPage) {
                        if ((visibleItemCount + firstVisibleItemPosition) >= totalItemCount
                                && firstVisibleItemPosition >= 0
                                && totalItemCount >= pageSize) {
                            loadMoreClothes();
                        }
                    }
                }
            }
        });
    }

    private void setupListeners() {
        // 下拉刷新
        swipeRefreshLayout.setOnRefreshListener(() -> {
            currentPage = 1;
            loadClothes(true);
        });
        
        // 添加衣物按钮
        fabAdd.setOnClickListener(v -> {
            if (!LoginCheckUtil.isLoggedIn(getActivity())) {
                // 未登录，显示登录对话框
                pendingLoginCallback = isLoggedIn -> {
                    if (isLoggedIn && getActivity() != null) {
                        navigateToAddClothes();
                    }
                };
                
                LoginCheckUtil.checkLoginWithDialog(getActivity(), "添加衣物需要登录，是否立即登录？", pendingLoginCallback);
            } else {
                navigateToAddClothes();
            }
        });
        
        // 添加分类按钮
        tvAddCategory.setOnClickListener(v -> {
            if (!categoryAdapter.isEditMode()) {
                if (!LoginCheckUtil.isLoggedIn(getActivity())) {
                    // 未登录，显示登录对话框
                    pendingLoginCallback = isLoggedIn -> {
                        if (isLoggedIn && getActivity() != null) {
                            showAddCategoryDialog();
                        }
                    };
                    
                    LoginCheckUtil.checkLoginWithDialog(getActivity(), "添加分类需要登录，是否立即登录？", pendingLoginCallback);
                } else {
                    showAddCategoryDialog();
                }
            }
        });
        
        // 完成编辑按钮
        tvFinishEdit.setOnClickListener(v -> {
            finishEditMode();
        });
        
        // 搜索输入框
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0) {
                    ivClearSearch.setVisibility(View.VISIBLE);
                } else {
                    ivClearSearch.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                searchKeyword = s.toString().trim();
            }
        });
        
        // 搜索按钮
        tvSearch.setOnClickListener(v -> {
            // 执行搜索
            currentPage = 1;
            isLastPage = false;
            loadClothes(true);
        });
        
        // 清除搜索按钮
        ivClearSearch.setOnClickListener(v -> {
            etSearch.setText("");
            searchKeyword = "";
            // 如果之前有搜索内容，执行搜索刷新
            if (!TextUtils.isEmpty(searchKeyword)) {
                currentPage = 1;
                isLastPage = false;
                loadClothes(true);
            }
        });
        
        // 搜索键盘提交
        etSearch.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                // 执行搜索
                currentPage = 1;
                isLastPage = false;
                loadClothes(true);
                return true;
            }
            return false;
        });
    }

    private void loadClothes(boolean isRefresh) {
        if (isLoading) return;
        
        // 添加登录状态检查
        if (!LoginCheckUtil.isLoggedIn(getActivity())) {
            Log.d(TAG, "用户未登录，停止加载衣物数据");
            // 停止加载状态
            isLoading = false;
            loadingLayout.setVisibility(View.GONE);
            swipeRefreshLayout.setRefreshing(false);
            
            // 清空数据并显示空状态
            if (isRefresh) {
                clothesList.clear();
                clothesAdapter.notifyDataSetChanged();
            }
            updateEmptyView();
            return;
        }
        
        isLoading = true;

        if (isRefresh) {
            clothesList.clear();
            clothesAdapter.notifyDataSetChanged();
            emptyStateLayout.setVisibility(View.GONE);
            tvNoMore.setVisibility(View.GONE);
        }

        loadingLayout.setVisibility(View.VISIBLE);

        // 获取当前选中的分类
        Category selectedCategory = categories.get(categoryAdapter.getSelectedPosition());
        // 获取当前选中的季节
        String selectedSeason = seasons.get(seasonAdapter.getSelectedPosition());
        if ("全部".equals(selectedSeason)) {
            selectedSeason = "all";
        } else if ("春季".equals(selectedSeason)) {
            selectedSeason = "spring";
        } else if ("夏季".equals(selectedSeason)) {
            selectedSeason = "summer";
        } else if ("秋季".equals(selectedSeason)) {
            selectedSeason = "autumn";
        } else if ("冬季".equals(selectedSeason)) {
            selectedSeason = "winter";
        }

        // 检查网络连接
        if (!NetworkUtil.isNetworkAvailable(getContext())) {
            // 网络不可用，加载本地缓存数据
            loadOfflineClothes(selectedCategory, selectedSeason);
            return;
        }

        // 调用真实API获取衣物列表
        loadClothesFromApi(selectedCategory, selectedSeason, isRefresh);

        lastRefreshTime = System.currentTimeMillis();
    }

    private void loadMoreClothes() {
        if (!isLoading && !isLastPage) {
            currentPage++;
            loadClothes(false);
        }
    }

    private void updateEmptyView() {
        if (clothesList.isEmpty()) {
            emptyStateLayout.setVisibility(View.VISIBLE);
        } else {
            emptyStateLayout.setVisibility(View.GONE);
        }
    }

    private void startEditMode() {
        Log.d(TAG, "开始编辑模式，当前分类数量: " + categories.size());

        // 打印所有分类信息
        for (int i = 0; i < categories.size(); i++) {
            Category cat = categories.get(i);
            Log.d(TAG, "编辑模式分类[" + i + "]: " + cat.getName() + " (ID: " + cat.getId() + ")");
        }

        categoryAdapter.setEditMode(true);
        tvFinishEdit.setVisibility(View.VISIBLE);

        // 添加按钮现在是固定的，不需要隐藏

        // 强制刷新适配器，确保所有分类都显示
        categoryAdapter.refreshData();

        Log.d(TAG, "编辑模式适配器项目数: " + categoryAdapter.getItemCount());

        // 显示提示信息，包含滑动提示和按钮说明
        Toast.makeText(getContext(), "可左右滑动查看所有分类\n红色×删除，绿色✎编辑，双击分类名也可编辑", Toast.LENGTH_LONG).show();
    }

    private void finishEditMode() {
        categoryAdapter.setEditMode(false);
        tvFinishEdit.setVisibility(View.GONE);

        Log.d(TAG, "退出编辑模式");

        // 显示退出提示
        Toast.makeText(getContext(), "已退出编辑模式", Toast.LENGTH_SHORT).show();
    }

    private void showAddCategoryDialog() {
        if (getContext() == null) return;
        
        View dialogView = LayoutInflater.from(getContext()).inflate(R.layout.dialog_add_category, null);
        EditText etCategoryName = dialogView.findViewById(R.id.etCategoryName);
        
        new MaterialAlertDialogBuilder(getContext())
                .setTitle("添加分类")
                .setView(dialogView)
                .setPositiveButton("添加", (dialog, which) -> {
                    String categoryName = etCategoryName.getText().toString().trim();
                    if (!TextUtils.isEmpty(categoryName)) {
                        addNewCategory(categoryName);
                    } else {
                        Toast.makeText(getContext(), "分类名称不能为空", Toast.LENGTH_SHORT).show();
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private void addNewCategory(String categoryName) {
        // 检查分类名称是否已存在
        for (Category category : categories) {
            if (category.getName().equals(categoryName)) {
                Toast.makeText(getContext(), "分类名称已存在", Toast.LENGTH_SHORT).show();
                return;
            }
        }

        // 创建分类请求对象
        CategoryRequest request = new CategoryRequest(categoryName);

        // 调用API添加分类
        ApiService apiService = ApiClient.getInstance().getApiService();
        apiService.addCategory(request).enqueue(new retrofit2.Callback<ApiResponse<Integer>>() {
            @Override
            public void onResponse(retrofit2.Call<ApiResponse<Integer>> call, retrofit2.Response<ApiResponse<Integer>> response) {
                if (getActivity() == null) return;

                if (response.isSuccessful() && response.body() != null) {
                    ApiResponse<Integer> apiResponse = response.body();

                    if (apiResponse.getCode() == 200 && apiResponse.getData() != null) {
                        // 服务器添加成功，创建新分类对象并添加到列表
                        Integer newCategoryId = apiResponse.getData();
                        Category newCategory = new Category(newCategoryId, categoryName);

                        // 添加到本地列表
                        categories.add(newCategory);

                        // 关键修复：更新适配器的数据源
                        if (categoryAdapter != null) {
                            categoryAdapter.setCategories(categories);
                            // 通知适配器数据变化
                            categoryAdapter.notifyItemInserted(categories.size() - 1);
                        }

                        // 再次强制刷新确保显示完整
                        categoryAdapter.refreshData();

                        // 保存到本地缓存
                        saveCategoriesLocal(categories);

                        Log.d(TAG, "分类添加成功，当前总数: " + categories.size() + ", 适配器项目数: " + categoryAdapter.getItemCount());
                        Toast.makeText(getContext(), "分类添加成功", Toast.LENGTH_SHORT).show();

                        // 通知其他Fragment分类数据已更新
                        notifyCategoryDataChanged();

                    } else {
                        Toast.makeText(getContext(), "添加失败: " + apiResponse.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(getContext(), "添加失败，请重试", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(retrofit2.Call<ApiResponse<Integer>> call, Throwable t) {
                if (getActivity() == null) return;
                Toast.makeText(getContext(), "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void showDeleteCategoryDialog(Category category, int position) {
        if (getContext() == null) return;
        
        new AlertDialog.Builder(getContext())
                .setTitle("删除分类")
                .setMessage("确定要删除分类" + category.getName() + "吗？")
                .setPositiveButton("删除", (dialog, which) -> deleteCategory(position))
                .setNegativeButton("取消", null)
                .show();
    }

    private void deleteCategory(int position) {
        if (position <= 0 || position >= categories.size()) return;

        Category category = categories.get(position);

        // 调用API删除分类
        ApiService apiService = ApiClient.getInstance().getApiService();
        apiService.deleteCategory(category.getId()).enqueue(new retrofit2.Callback<ApiResponse<Boolean>>() {
            @Override
            public void onResponse(retrofit2.Call<ApiResponse<Boolean>> call, retrofit2.Response<ApiResponse<Boolean>> response) {
                if (getActivity() == null) return;

                if (response.isSuccessful() && response.body() != null) {
                    ApiResponse<Boolean> apiResponse = response.body();

                    if (apiResponse.getCode() == 200 && Boolean.TRUE.equals(apiResponse.getData())) {
                        // 服务器删除成功，更新本地数据
                        categories.remove(position);

                        // 关键修复：更新适配器的数据源
                        if (categoryAdapter != null) {
                            categoryAdapter.setCategories(categories);
                            // 更新适配器
                            categoryAdapter.notifyItemRemoved(position);
                        }

                        // 再次强制刷新确保显示完整
                        categoryAdapter.refreshData();

                        // 如果删除的是当前选中的分类，切换到"全部"分类
                        if (categoryAdapter.getSelectedPosition() == position) {
                            categoryAdapter.setSelectedPosition(0);
                            currentPage = 1;
                            isLastPage = false;
                            loadClothes(true);
                        }

                        // 保存到本地
                        saveCategoriesLocal(categories);

                        Log.d(TAG, "分类删除成功，当前总数: " + categories.size() + ", 适配器项目数: " + categoryAdapter.getItemCount());
                        Toast.makeText(getContext(), "分类删除成功", Toast.LENGTH_SHORT).show();

                        // 通知其他Fragment分类数据已更新
                        notifyCategoryDataChanged();

                        // 删除成功后不自动退出编辑模式，让用户可以继续删除其他分类
                        // 用户可以点击"完成"按钮或点击分类项退出编辑模式

                    } else {
                        Toast.makeText(getContext(), "删除失败: " + apiResponse.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(getContext(), "删除失败，请重试", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(retrofit2.Call<ApiResponse<Boolean>> call, Throwable t) {
                if (getActivity() == null) return;
                Toast.makeText(getContext(), "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    
    private void navigateToAddClothes() {
        // 跳转到添加衣物页面
        Intent intent = new Intent(getActivity(), AddClothesActivity.class);
        startActivity(intent);
    }

    private void showClothesDetail(Clothes clothes) {
        // 跳转到衣物详情页面
        Intent intent = new Intent(getActivity(), ClothesDetailActivity.class);
        intent.putExtra("clothes_id", clothes.getId());
        startActivity(intent);
    }
    
    // 从本地读取分类
    private List<Category> getCategoriesFromLocal() {
        if (getContext() == null) return null;
        
        SharedPreferences sp = getContext().getSharedPreferences("wardrobe_data", Context.MODE_PRIVATE);
        String categoriesJson = sp.getString("categories", null);
        
        if (TextUtils.isEmpty(categoriesJson)) return null;
        
        try {
            Gson gson = new Gson();
            Type type = new TypeToken<List<Category>>(){}.getType();
            return gson.fromJson(categoriesJson, type);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    // 保存分类到本地
    private void saveCategoriesLocal(List<Category> categories) {
        if (getContext() == null || categories == null) return;
        
        // 过滤掉"全部"分类
        List<Category> saveList = new ArrayList<>();
        for (Category category : categories) {
            if (category.getId() != 0) {
                saveList.add(category);
            }
        }
        
        try {
            Gson gson = new Gson();
            String categoriesJson = gson.toJson(saveList);
            
            SharedPreferences sp = getContext().getSharedPreferences("wardrobe_data", Context.MODE_PRIVATE);
            sp.edit().putString("categories", categoriesJson).apply();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    // 保存衣物到本地缓存
    private void saveClothesToCache(List<Clothes> clothesList) {
        if (getContext() == null || clothesList == null) return;
        
        try {
            Gson gson = new Gson();
            String clothesJson = gson.toJson(clothesList);
            
            SharedPreferences sp = getContext().getSharedPreferences("wardrobe_data", Context.MODE_PRIVATE);
            sp.edit().putString("clothes_cache", clothesJson).apply();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    // 从本地缓存加载衣物
    private List<Clothes> getClothesFromCache() {
        if (getContext() == null) return new ArrayList<>();
        
        SharedPreferences sp = getContext().getSharedPreferences("wardrobe_data", Context.MODE_PRIVATE);
        String clothesJson = sp.getString("clothes_cache", null);
        
        if (TextUtils.isEmpty(clothesJson)) return new ArrayList<>();
        
        try {
            Gson gson = new Gson();
            Type type = new TypeToken<List<Clothes>>(){}.getType();
            return gson.fromJson(clothesJson, type);
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }
    
    // 离线模式加载衣物
    private void loadOfflineClothes(Category selectedCategory, String selectedSeason) {
        List<Clothes> cachedClothes = getClothesFromCache();
        List<Clothes> filteredClothes = new ArrayList<>();
        
        // 根据分类和季节筛选衣物
        for (Clothes clothes : cachedClothes) {
            boolean categoryMatch = selectedCategory.getId() == 0 || 
                    (clothes.getCategory() != null && 
                    clothes.getCategory().equals(selectedCategory.getName()));
            
            boolean seasonMatch = "all".equals(selectedSeason) || 
                    (clothes.getSeason() != null && 
                    clothes.getSeason().equals(selectedSeason));
            
            boolean searchMatch = TextUtils.isEmpty(searchKeyword) || 
                    (clothes.getName() != null && 
                    clothes.getName().toLowerCase().contains(searchKeyword.toLowerCase()));
            
            if (categoryMatch && seasonMatch && searchMatch) {
                filteredClothes.add(clothes);
            }
        }
        
        // 主线程更新UI
        if (getActivity() != null) {
            getActivity().runOnUiThread(() -> {
                clothesList.clear();
                clothesList.addAll(filteredClothes);
                clothesAdapter.notifyDataSetChanged();
                
                isLoading = false;
                isLastPage = true;
                loadingLayout.setVisibility(View.GONE);
                swipeRefreshLayout.setRefreshing(false);
                
                if (filteredClothes.size() > 0) {
                    tvNoMore.setVisibility(View.VISIBLE);
                }
                
                updateEmptyView();
                
                Toast.makeText(getContext(), "网络不可用，显示缓存数据", Toast.LENGTH_SHORT).show();
            });
        }
    }

    private List<Clothes> getSimulatedClothes(int page, int categoryId, String season) {
        List<Clothes> result = new ArrayList<>();
        
        // 模拟数据
        String[] categories = {"上衣", "裤子", "裙子", "外套", "鞋子", "配饰"};
        String[] names = {"经典白T恤", "牛仔短裤", "碎花连衣裙", "休闲夹克", "运动鞋", "项链", 
                "格子衬衫", "黑色西裤", "百褶裙", "羽绒服", "高跟鞋", "耳环"};
        
        // 根据分类和季节筛选
        Random random = new Random();
        int start = (page - 1) * pageSize;
        int count = Math.min(pageSize, 50 - start); // 假设总共有50件衣物
        
        if (start >= 50) {
            return result; // 没有更多数据
        }
        
        for (int i = 0; i < count; i++) {
            int id = start + i + 1;
            
            // 获取分类名称
            String category = categoryId == 0 ? 
                    categories[random.nextInt(categories.length)] : 
                    getCategoryNameById(categoryId);
            
            // 生成对应季节的衣物
            String itemSeason;
            if ("all".equals(season)) {
                itemSeason = getSeasonByIndex(random.nextInt(4));
            } else {
                itemSeason = season;
            }
            
            // 处理搜索关键词
            String name = names[random.nextInt(names.length)] + " " + id;
            if (!TextUtils.isEmpty(searchKeyword) && !name.toLowerCase().contains(searchKeyword.toLowerCase())) {
                // 如果有搜索关键词但名称不匹配，则跳过
                i--;
                continue;
            }
            
            // 创建衣物对象
            Clothes clothes = new Clothes(id, name, category, 
                    "https://via.placeholder.com/300/FFC0CB/000000?text=" + id, itemSeason);
            
            result.add(clothes);
        }
        
        return result;
    }

    private String getCategoryNameById(int categoryId) {
        for (Category category : categories) {
            if (category.getId() == categoryId) {
                return category.getName();
            }
        }
        return "";
    }

    private String getSeasonByIndex(int index) {
        String[] seasonValues = {"spring", "summer", "autumn", "winter"};
        return seasonValues[index % seasonValues.length];
    }

    /**
     * 从API加载衣物列表
     * @param selectedCategory 选中的分类
     * @param selectedSeason 选中的季节
     * @param isRefresh 是否为刷新操作
     */
    private void loadClothesFromApi(Category selectedCategory, String selectedSeason, boolean isRefresh) {
        // 准备API调用参数
        Integer categoryId = selectedCategory.getId() != 0 ? selectedCategory.getId() : null;
        String season = !"all".equals(selectedSeason) ? selectedSeason : null;
        String keyword = !TextUtils.isEmpty(searchKeyword) ? searchKeyword : null;

        Log.d(TAG, "发起API请求 - 页码: " + currentPage + ", 分类ID: " + categoryId +
                ", 季节: " + season + ", 关键词: " + keyword);

        // 使用ApiService调用API
        ApiService apiService = ApiClient.getInstance().getApiService();

        // 调用API
        apiService.getClothesList(
                currentPage,
                pageSize,
                categoryId,
                season,
                keyword
        ).enqueue(new retrofit2.Callback<ApiResponse<ClothesListResponse>>() {
            @Override
            public void onResponse(retrofit2.Call<ApiResponse<ClothesListResponse>> call,
                                 retrofit2.Response<ApiResponse<ClothesListResponse>> response) {
                if (getActivity() == null) return;

                if (response.isSuccessful() && response.body() != null) {
                    ApiResponse<ClothesListResponse> apiResponse = response.body();

                    if (apiResponse.getCode() == 200 && apiResponse.getData() != null) {
                        ClothesListResponse data = apiResponse.getData();
                        List<Clothes> newClothes = data.getList();

                        Log.d(TAG, "API请求成功，获取到 " + (newClothes != null ? newClothes.size() : 0) + " 条数据");

                        if (newClothes == null) {
                            newClothes = new ArrayList<>();
                        }

                        if (isRefresh) {
                            clothesList.clear();
                        }

                        // 添加新数据
                        clothesList.addAll(newClothes);
                        clothesAdapter.notifyDataSetChanged();

                        // 保存到本地缓存
                        saveClothesToCache(clothesList);

                        // 更新UI状态
                        isLoading = false;
                        loadingLayout.setVisibility(View.GONE);
                        swipeRefreshLayout.setRefreshing(false);

                        // 判断是否还有更多数据
                        int total = data.getTotal();
                        boolean hasMore = clothesList.size() < total;

                        if (!hasMore || newClothes.size() < pageSize) {
                            isLastPage = true;
                            if (clothesList.size() > 0) {
                                tvNoMore.setVisibility(View.VISIBLE);
                            }
                        } else {
                            isLastPage = false;
                            tvNoMore.setVisibility(View.GONE);
                        }

                        // 更新空视图状态
                        updateEmptyView();

                        Log.d(TAG, "衣物列表更新完成，当前总数: " + clothesList.size() + ", 服务器总数: " + total);
                    } else {
                        // API返回错误
                        handleApiError(apiResponse.getCode(), apiResponse.getMessage(), selectedCategory, selectedSeason, isRefresh);
                    }
                } else {
                    // HTTP请求失败
                    handleApiError(response.code(), "HTTP请求失败", selectedCategory, selectedSeason, isRefresh);
                }
            }

            @Override
            public void onFailure(retrofit2.Call<ApiResponse<ClothesListResponse>> call, Throwable t) {
                Log.e(TAG, "API请求失败: " + t.getMessage(), t);
                if (getActivity() == null) return;

                handleApiError(500, "网络请求失败: " + t.getMessage(), selectedCategory, selectedSeason, isRefresh);
            }
        });
    }

    /**
     * 处理API错误
     */
    private void handleApiError(int code, String message, Category selectedCategory, String selectedSeason, boolean isRefresh) {
        // 更新UI状态
        isLoading = false;
        loadingLayout.setVisibility(View.GONE);
        swipeRefreshLayout.setRefreshing(false);

        // 如果是网络错误，尝试加载缓存数据
        if (code == 500 && isRefresh) {
            Log.d(TAG, "网络错误，尝试加载缓存数据");
            loadOfflineClothes(selectedCategory, selectedSeason);
            Toast.makeText(getContext(), "网络连接失败，显示缓存数据", Toast.LENGTH_SHORT).show();
        } else {
            // 显示错误信息
            String errorMsg = "加载失败";
            if (code == 401) {
                errorMsg = "登录已过期，请重新登录";
            } else if (!TextUtils.isEmpty(message)) {
                errorMsg = message;
            }

            Toast.makeText(getContext(), errorMsg, Toast.LENGTH_SHORT).show();
            updateEmptyView();
        }
    }

    /**
     * 从本地存储获取用户token
     * @return 用户token，如果未登录则返回null
     */
    private String getTokenFromStorage() {
        if (getContext() == null) return null;

        SharedPreferences sp = getContext().getSharedPreferences("user_data", Context.MODE_PRIVATE);
        return sp.getString("token", null);
    }

    /**
     * 从API加载分类列表
     * 参考UniApp项目中的categoryApi.getCategoryList方法
     */
    private void loadCategoriesFromApi() {
        ApiService apiService = ApiClient.getInstance().getApiService();

        apiService.getCategoryList().enqueue(new retrofit2.Callback<ApiResponse<List<Category>>>() {
            @Override
            public void onResponse(retrofit2.Call<ApiResponse<List<Category>>> call,
                                 retrofit2.Response<ApiResponse<List<Category>>> response) {
                if (getActivity() == null) return;

                if (response.isSuccessful() && response.body() != null) {
                    ApiResponse<List<Category>> apiResponse = response.body();

                    Log.d(TAG, "分类接口响应: code=" + apiResponse.getCode() + ", message=" + apiResponse.getMessage());

                    if (apiResponse.getCode() == 200 && apiResponse.getData() != null) {
                        List<Category> serverCategories = apiResponse.getData();

                        Log.d(TAG, "WardrobeFragment服务器返回分类数量: " + serverCategories.size());

                        // 打印服务器返回的分类详情
                        for (int i = 0; i < serverCategories.size(); i++) {
                            Category cat = serverCategories.get(i);
                            Log.d(TAG, "WardrobeFragment服务器分类[" + i + "]: " + cat.getName() + " (ID: " + cat.getId() + ")");
                        }

                        // 保存当前选中的分类ID
                        int selectedCategoryId = categoryAdapter != null ? categoryAdapter.getSelectedCategoryId() : 0;

                        // 完全重建分类列表，确保数据完整性
                        categories.clear();

                        // 添加"全部"分类
                        categories.add(new Category(0, "全部"));

                        // 添加从服务器获取的分类
                        categories.addAll(serverCategories);

                        Log.d(TAG, "WardrobeFragment分类列表重建完成，当前总数: " + categories.size());

                        // 打印当前分类列表详情
                        for (int i = 0; i < categories.size(); i++) {
                            Category cat = categories.get(i);
                            Log.d(TAG, "WardrobeFragment当前分类[" + i + "]: " + cat.getName() + " (ID: " + cat.getId() + ")");
                        }

                        // 简化的适配器刷新逻辑
                        if (categoryAdapter != null) {
                            Log.d(TAG, "开始刷新分类适配器，分类总数: " + categories.size());

                            // 直接设置新的分类列表
                            categoryAdapter.setCategories(categories);

                            // 强制刷新所有数据
                            categoryAdapter.notifyDataSetChanged();

                            Log.d(TAG, "分类适配器刷新完成，适配器项目数: " + categoryAdapter.getItemCount());

                            // 恢复选中状态
                            restoreSelectedCategory(selectedCategoryId);
                        } else {
                            Log.w(TAG, "WardrobeFragment categoryAdapter为null，无法刷新");
                        }

                        // 保存到本地缓存
                        saveCategoriesLocal(categories);

                        Log.d(TAG, "WardrobeFragment分类列表更新成功，最终总数: " + categories.size() + "个分类（包含全部）");

                        // 显示分类数量提示并测试滚动功能
                        if (getActivity() != null) {
                            getActivity().runOnUiThread(() -> {
                                if (categories.size() > 5) {
                                    Toast.makeText(getContext(), "共" + categories.size() + "个分类，可左右滑动查看全部", Toast.LENGTH_SHORT).show();

                                    // 测试滚动功能
                                    rvCategories.post(() -> {
                                        int totalWidth = 0;
                                        for (int i = 0; i < categoryAdapter.getItemCount(); i++) {
                                            View child = rvCategories.getLayoutManager().findViewByPosition(i);
                                            if (child != null) {
                                                totalWidth += child.getWidth();
                                            }
                                        }
                                        Log.d(TAG, "RecyclerView总宽度: " + totalWidth + ", 可见宽度: " + rvCategories.getWidth());
                                        Log.d(TAG, "是否可以滚动: " + rvCategories.canScrollHorizontally(1));
                                    });
                                }
                            });
                        }
                    } else {
                        Log.e(TAG, "分类列表加载失败: " + apiResponse.getMessage());
                        // API返回错误，使用默认分类
                        loadCategoriesFromLocal();
                    }
                } else {
                    Log.e(TAG, "分类列表请求失败，HTTP状态码: " + response.code());
                    // HTTP请求失败，使用默认分类
                    loadCategoriesFromLocal();
                }
            }

            @Override
            public void onFailure(retrofit2.Call<ApiResponse<List<Category>>> call, Throwable t) {
                if (getActivity() == null) return;

                // 网络请求失败，尝试从本地加载
                loadCategoriesFromLocal();
            }
        });
    }

    /**
     * 从本地加载分类列表作为后备方案
     */
    private void loadCategoriesFromLocal() {
        List<Category> savedCategories = getCategoriesFromLocal();
        if (savedCategories != null && !savedCategories.isEmpty()) {
            // 清除除了"全部"分类之外的其他分类
            while (categories.size() > 1) {
                categories.remove(1);
            }

            // 添加本地保存的分类
            categories.addAll(savedCategories);

            // 通知适配器数据已更改
            categoryAdapter.notifyDataSetChanged();
        } else {
            // 如果本地也没有，使用默认分类
            loadDefaultCategories();
        }
    }

    /**
     * 加载默认分类
     */
    private void loadDefaultCategories() {
        // 清除除了"全部"分类之外的其他分类
        while (categories.size() > 1) {
            categories.remove(1);
        }

        // 添加默认分类
        categories.add(new Category(1, "上衣"));
        categories.add(new Category(2, "裤子"));
        categories.add(new Category(3, "裙子"));
        categories.add(new Category(4, "外套"));
        categories.add(new Category(5, "鞋子"));
        categories.add(new Category(6, "配饰"));

        // 通知适配器数据已更改
        categoryAdapter.notifyDataSetChanged();

        // 保存到本地
        saveCategoriesLocal(categories);
    }

    /**
     * 检查是否需要在登录后刷新数据
     */
    private void checkAndRefreshAfterLogin() {
        if (getContext() != null) {
            boolean needRefreshAfterLogin = getContext().getSharedPreferences("app_state", Context.MODE_PRIVATE)
                    .getBoolean("need_refresh_after_login", false);

            if (needRefreshAfterLogin) {
                Log.d(TAG, "检测到登录后需要刷新，开始刷新数据");
                refreshDataAfterLogin();

                // 清除标记
                getContext().getSharedPreferences("app_state", Context.MODE_PRIVATE)
                        .edit()
                        .putBoolean("need_refresh_after_login", false)
                        .apply();
            }
        }
    }

    /**
     * 编辑分类
     * @param category 要编辑的分类
     * @param position 分类在列表中的位置
     */
    private void editCategory(Category category, int position) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle("编辑分类名称");

        // 创建输入框
        final EditText input = new EditText(getContext());
        input.setInputType(InputType.TYPE_CLASS_TEXT);
        input.setText(category.getName());
        input.setSelection(category.getName().length()); // 光标移到末尾
        input.setHint("请输入分类名称");

        // 设置输入框的样式
        input.setPadding(50, 30, 50, 30);
        builder.setView(input);

        // 设置按钮 - 注意按钮顺序，积极操作在右边
        builder.setNegativeButton("取消", (dialog, which) -> {
            dialog.dismiss();
            // 隐藏键盘
            hideKeyboard(input);
        });

        builder.setPositiveButton("保存", (dialog, which) -> {
            String newName = input.getText().toString().trim();
            if (!newName.isEmpty()) {
                if (!newName.equals(category.getName())) {
                    updateCategory(category.getId(), newName, position);
                } else {
                    Toast.makeText(getContext(), "分类名称未改变", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(getContext(), "分类名称不能为空", Toast.LENGTH_SHORT).show();
            }
            // 隐藏键盘
            hideKeyboard(input);
        });

        // 设置对话框不可取消（必须点击按钮）
        builder.setCancelable(false);

        AlertDialog dialog = builder.create();

        // 设置Enter键监听
        input.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_DONE ||
                (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                // 模拟点击保存按钮
                String newName = input.getText().toString().trim();
                if (!newName.isEmpty()) {
                    if (!newName.equals(category.getName())) {
                        updateCategory(category.getId(), newName, position);
                    } else {
                        Toast.makeText(getContext(), "分类名称未改变", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(getContext(), "分类名称不能为空", Toast.LENGTH_SHORT).show();
                }
                dialog.dismiss();
                hideKeyboard(input);
                return true;
            }
            return false;
        });

        dialog.show();

        // 自动弹出键盘并聚焦
        input.requestFocus();
        dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

        // 延迟显示键盘，确保对话框完全显示
        input.postDelayed(() -> {
            InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm != null) {
                imm.showSoftInput(input, InputMethodManager.SHOW_IMPLICIT);
            }
        }, 100);
    }

    /**
     * 隐藏软键盘
     */
    private void hideKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    /**
     * 更新分类
     * @param categoryId 分类ID
     * @param newName 新名称
     * @param position 分类在列表中的位置
     */
    private void updateCategory(Integer categoryId, String newName, int position) {
        // 检查分类名称是否已存在
        for (int i = 0; i < categories.size(); i++) {
            if (i != position && categories.get(i).getName().equals(newName)) {
                Toast.makeText(getContext(), "分类名称已存在", Toast.LENGTH_SHORT).show();
                return;
            }
        }

        // 创建更新请求
        CategoryRequest request = new CategoryRequest(newName);

        // 调用API更新分类
        ApiService apiService = ApiClient.getInstance().getApiService();
        apiService.updateCategory(categoryId, request).enqueue(new retrofit2.Callback<ApiResponse<Boolean>>() {
            @Override
            public void onResponse(retrofit2.Call<ApiResponse<Boolean>> call, retrofit2.Response<ApiResponse<Boolean>> response) {
                if (getActivity() == null) return;

                if (response.isSuccessful() && response.body() != null) {
                    ApiResponse<Boolean> apiResponse = response.body();

                    if (apiResponse.getCode() == 200 && Boolean.TRUE.equals(apiResponse.getData())) {
                        // 服务器更新成功，更新本地数据
                        categories.get(position).setName(newName);

                        // 关键修复：更新适配器的数据源
                        if (categoryAdapter != null) {
                            categoryAdapter.setCategories(categories);
                            categoryAdapter.notifyItemChanged(position);
                        }

                        // 再次强制刷新确保显示完整
                        categoryAdapter.refreshData();

                        // 保存到本地
                        saveCategoriesLocal(categories);

                        Log.d(TAG, "分类编辑成功，当前总数: " + categories.size() + ", 适配器项目数: " + categoryAdapter.getItemCount());
                        Toast.makeText(getContext(), "分类更新成功", Toast.LENGTH_SHORT).show();

                        // 通知其他Fragment分类数据已更新
                        notifyCategoryDataChanged();

                    } else {
                        Toast.makeText(getContext(), "更新失败: " + apiResponse.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(getContext(), "更新失败，请重试", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(retrofit2.Call<ApiResponse<Boolean>> call, Throwable t) {
                if (getActivity() == null) return;
                Toast.makeText(getContext(), "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 登录后刷新数据
     * 重新加载分类和衣物数据，确保显示用户的最新数据
     */
    public void refreshDataAfterLogin() {
        Log.d(TAG, "登录后刷新数据开始");

        // 临时调试：检查token状态和测试分类接口
        if (getContext() != null) {
            Log.d(TAG, "=== 开始Token调试 ===");
            TokenDebugHelper.checkTokenStatus(getContext());
            TokenDebugHelper.testCategoryApiWithToken(getContext());
        }

        // 重新加载分类数据
        setupCategories();

        // 重新加载衣物数据
        currentPage = 1;
        isLastPage = false;
        loadClothes(true);

        Log.d(TAG, "登录后刷新数据完成");
    }

    /**
     * 刷新分类数据
     * 重新从服务器加载分类列表
     */
    public void refreshCategories() {
        Log.d(TAG, "刷新分类数据");
        loadCategoriesFromApi();
    }

    /**
     * 恢复选中的分类
     */
    private void restoreSelectedCategory(int selectedCategoryId) {
        if (categoryAdapter == null) return;

        // 查找对应的分类位置
        for (int i = 0; i < categories.size(); i++) {
            if (categories.get(i).getId() == selectedCategoryId) {
                categoryAdapter.setSelectedPosition(i);
                categoryAdapter.setSelectedCategoryId(selectedCategoryId);
                Log.d(TAG, "恢复选中分类: " + categories.get(i).getName() + " (位置: " + i + ")");
                return;
            }
        }

        // 如果没找到，默认选中"全部"
        categoryAdapter.setSelectedPosition(0);
        categoryAdapter.setSelectedCategoryId(0);
        Log.d(TAG, "未找到之前选中的分类，默认选中全部");
    }

    /**
     * 强制刷新分类数据
     * 每次Fragment可见时都重新加载，确保数据完整
     */
    private void forceRefreshCategoriesIfNeeded() {
        if (getActivity() == null) return;

        Log.d(TAG, "WardrobeFragment强制检查分类数据");
        Log.d(TAG, "当前分类数量: " + categories.size());

        // 打印当前分类列表
        for (int i = 0; i < categories.size(); i++) {
            Category cat = categories.get(i);
            Log.d(TAG, "WardrobeFragment onResume当前分类[" + i + "]: " + cat.getName() + " (ID: " + cat.getId() + ")");
        }

        // 如果用户已登录，强制重新加载分类数据
        if (LoginCheckUtil.isLoggedIn(getActivity())) {
            Log.d(TAG, "WardrobeFragment用户已登录，强制重新加载分类数据");
            loadCategoriesFromApi();
        } else {
            Log.d(TAG, "WardrobeFragment用户未登录，使用默认分类");
            loadCategoriesFromLocal();
        }

        // 额外的强制刷新，确保UI显示完整
        if (categoryAdapter != null && categories.size() > 0) {
            categoryAdapter.setCategories(categories);
            categoryAdapter.notifyDataSetChanged();
            Log.d(TAG, "forceRefreshCategoriesIfNeeded - 强制刷新完成");
        }
    }

    /**
     * 检查分类数据完整性（保留原方法作为备用）
     * 如果数据不完整则重新加载
     */
    private void checkAndLoadCategoriesIfNeeded() {
        if (getActivity() == null) return;

        // 如果用户已登录但分类数据不完整，则重新加载
        if (LoginCheckUtil.isLoggedIn(getActivity())) {
            if (categories.size() <= 1) {
                Log.d(TAG, "用户已登录但分类数据不完整，重新加载");
                loadCategoriesFromApi();
            } else {
                Log.d(TAG, "分类数据完整，当前分类数量: " + categories.size());
            }
        } else {
            Log.d(TAG, "用户未登录，使用默认分类");
        }
    }

    /**
     * 通知其他Fragment分类数据已更新
     */
    private void notifyCategoryDataChanged() {
        if (getActivity() instanceof MainActivity) {
            ((MainActivity) getActivity()).refreshCategoriesInAllFragments();
        }
    }
}